package org.example.rzfx.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.example.rzfx.entity.LogParseRule;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 日志解析工具类
 */
public class LogParseUtil {
    
    /**
     * 根据解析规则解析日志内容
     */
    public static Map<String, String> parseLog(String content, LogParseRule rule) {
        Map<String, String> result = new HashMap<>();
        
        try {
            Pattern pattern = Pattern.compile(rule.getRegexPattern());
            Matcher matcher = pattern.matcher(content);
            
            if (matcher.find()) {
                // 解析字段映射
                JSONObject fieldMapping = JSON.parseObject(rule.getFieldMapping());
                
                // 根据字段映射提取数据
                for (String key : fieldMapping.keySet()) {
                    int groupIndex = Integer.parseInt(key);
                    String fieldName = fieldMapping.getString(key);
                    
                    if (groupIndex <= matcher.groupCount()) {
                        String value = matcher.group(groupIndex);
                        result.put(fieldName, value);
                    }
                }
            }
        } catch (Exception e) {
            // 解析失败，返回空结果
            e.printStackTrace();
        }
        
        return result;
    }
    
    /**
     * 根据正则表达式快速解析
     */
    public static Map<String, String> parseLogByRegex(String content, String regex, Map<Integer, String> fieldMap) {
        Map<String, String> result = new HashMap<>();
        
        try {
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(content);
            
            if (matcher.find()) {
                for (Map.Entry<Integer, String> entry : fieldMap.entrySet()) {
                    int groupIndex = entry.getKey();
                    String fieldName = entry.getValue();
                    
                    if (groupIndex <= matcher.groupCount()) {
                        String value = matcher.group(groupIndex);
                        result.put(fieldName, value);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return result;
    }
    
    /**
     * 提取日志级别
     */
    public static String extractLogLevel(String content) {
        String[] levels = {"DEBUG", "INFO", "WARN", "ERROR", "FATAL"};
        
        for (String level : levels) {
            if (content.toUpperCase().contains(level)) {
                return level;
            }
        }
        
        return "INFO"; // 默认INFO级别
    }
}

